﻿using BlazorAdmin.Services.DbService;
using Microsoft.Extensions.DependencyInjection;
using Pangeo.Admin.Interface.HrmDb;
using Pangeo.Admin.Models.BaBizDb.Entity;

namespace Pangeo.Admin.Tasks.Jobs
{
    public class SyncQrqcEmailUser
    {
        private readonly IHrm hrmService;
        private readonly IServiceScopeFactory scopeFactory;
        private readonly ISqlSugar BaBizDb;

        public SyncQrqcEmailUser(IServiceScopeFactory _scopeFactory)
        {
            using (var scope = _scopeFactory.CreateScope())
            {
                hrmService = scope.ServiceProvider.GetRequiredService<IHrm>();
                BaBizDb = scope.ServiceProvider.GetRequiredService<ISqlSugar>();
            }

            scopeFactory = _scopeFactory;
        }

        /// <summary>
        /// 推送班次数据到BI
        /// </summary>
        public async Task Run()
        {
            var users = await hrmService.GetQrqcEmailUser();
            var db = BaBizDb.Create();

            try
            {

                db.Ado.BeginTran();

                db.Deleteable<QrqcEmailUser>().ExecuteCommand();

                users.ForEach(t => db.Insertable(t));

                db.Ado.CommitTran();
            }
            catch (Exception ex)
            {
                db.Ado.RollbackTran();

                throw ex; // 抛出异常，定时任务会捕获到，标记：执行失败
            }
        }
    }
}